package com.tul.vapp.servicecenter.client;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.I0Itec.zkclient.exception.ZkNoNodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tul.cusa.zookeeper.IZookeeperClient;
import com.tul.vapp.servicecenter.utils.ConfigUtil;
import com.tul.vapp.servicecenter.zookeeper.ZooKeeperClientFactory;

/**
 * ZkService
 * 
 * @author wwxiang
 * @since 2018/4/17.
 */
public class ZkService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ZkService.class);

	private static final String ROOT = "/config";

	private static final String SEPARATOR = "/";

	private IZookeeperClient client;

	private static ZkService zkService;

	private ZkService() {
		client = ZooKeeperClientFactory.getClient();
	}

	/**
	 * 单例获取ZK服务
	 * 
	 * @return ZkService
	 */
	public static ZkService getInstance() {
		if (zkService == null) {
			zkService = new ZkService();
		}
		return zkService;
	}

	/**
	 * 根据appId能够从ZK上获取其下所有的命名空间
	 *
	 * @param appNode 应用名称
	 * @return 命名空间列表
	 */
	public List<String> getNamespaces(String appNode) {
		String appPath = ROOT + SEPARATOR + appNode;
		return client.getChildren(appPath);
	}

	/**
	 * 根据appNode namespace 获取配置内容
	 * 
	 * @param appNode appNode
	 * @param namespace namespace
	 * @return Map
	 * @throws IOException e
	 */
	public Map<String, String> getProperties(String appNode, String namespace) throws IOException {
		String nsPath = ROOT + SEPARATOR + appNode + SEPARATOR + namespace;
		byte[] bytes = null;
		try {
			bytes = client.getData(nsPath);
		} catch (ZkNoNodeException e) {
			LOGGER.warn(nsPath + " not exists");
		}
		Map<String, String> result = new HashMap();
		if (bytes != null) {
			String content = new String(bytes);
			Properties props = ConfigUtil.parse(content);
			result = ConfigUtil.format(props);
		}
		return result;
	}
}
